/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.util;

import java.util.*;

import java.net.*;

import javax.servlet.ServletRequest;

/**
 * Utility class used by services to limit access to them. For example, a guestbook service can limit how often an entry can be written from the same user/ip address.
 */
public class ServiceIPLimiter extends HashMap //TODO Categorizar bags
{
	private static org.apache.commons.logging.Log log =
		org.apache.commons.logging.LogFactory.getLog(ServiceIPLimiter.class.getName());

	int defaultMinimumGap = 60; //Cada minuto.

	public boolean checkaccess(String portalid, Integer serviceCategoryId, ServletRequest request)
	{
		return checkaccess(portalid, serviceCategoryId, request, defaultMinimumGap);
	}

	public boolean checkaccess(String portalid, Integer serviceCategoryId, ServletRequest request, int seconds)
	{
		HashMap ids = (HashMap)get(portalid); // Cogemos los accesos a los servicios para este portal.
		if (ids == null)
			ids = new HashMap();
		HashMap addresses =
			(HashMap)ids.get(serviceCategoryId); // Cogemos los accesos por IP para el servicio pkey (generalmente, el pkey de la categoría en cuestión)
		if (addresses == null)
			addresses = new HashMap();
		try
		{
			InetAddress inetaddress = InetAddress.getByName(request.getRemoteHost());
			Long lastusage =
				(Long)addresses.get(inetaddress); // Cogemos cuándo se ha accedido por última vez a este servicio desde esa IP
			long now = new Date().getTime();
			boolean allowed = true;
			if (lastusage != null)
				allowed = lastusage.longValue() + (seconds * 1000) < now;
			log.debug("Lastusage: " + lastusage + " for serviceCategoryId " + serviceCategoryId + ", " + now + ": allowed:" + allowed);
			addresses.put(inetaddress, new Long(now)); // Ponemos el último uso (ahora) en la lista
			ids.put(serviceCategoryId, addresses);
			put(portalid, ids);
			return allowed;
		} catch (UnknownHostException e)
		{
			throw new IllegalArgumentException(e.getMessage());
		}
	}
}
